/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bankingsystem;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * This class provides the template for the PersistenceManager object which is used to
 * store the given Bank object to the disk on demand.
 * @author Gokul
 * @version 1.0
 */

public class PersistenceManager {

    private FileOutputStream fos;
    private ObjectOutputStream oos;
    private FileInputStream fis;
    private ObjectInputStream ois;

    /**
     * Receives a Bank object as an input and writes it onto the disk.
     * @param b the Bank object that is to be serialized.
     */
    public void savedata(Bank b){
        try {
            /*initializing streams and using them to write the Bank object. The name of the file
            that is being used to store the object is "BankRecords.dat"*/
            fos = new FileOutputStream("BankRecords.dat");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(b);

            /*flushing and closing streams*/
            oos.flush();
            oos.close();
            fos.close();
            
        } catch (Exception ex) {
            /*If an error occurred while saving data, output the following error message.*/
            System.out.println("An error occurred while saving data.");
        }

    }
    /**
     * Reads a previously stored BankRecords file and extracts the needed
     * Bank object from it.
     *
     * @return the bank object that was read from the file.
     */
    public Bank readData(){
        Bank b = null;              /*initializing the Bank object*/
        try {
            /*try to use the inputstreams to read the object from the specified file.*/
            fis = new FileInputStream("BankRecords.dat");
            ois = new ObjectInputStream(fis);
            b = (Bank) ois.readObject();
            /*closing */
            ois.close();
            fis.close();

        } catch (Exception ex) {
            /*if an error occurred, warn the user that the read operation failed and
            return a null object so that it can be checked later by the reliant classes for
            validity.*/
            System.out.println("An error occurred while reading data.");
            
        }
        /*Return the object that was read. This can either be a valid Bank object or a null value.
         The returned object is handled accordingly by the entity calling this method.*/
        return b;
    }
}
